import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/components/calendar_btn_icon.dart';
import 'package:share_fit/app/components/date_type_bar.dart';
import 'package:share_fit/app/components/stacked_line_indicator.dart';
import 'package:share_fit/app/components/table_calendar_dialog.dart';
import 'package:share_fit/app/controllers/home/heart_rate/components/hr_line_chart.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/home/date_type_enum.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'logic.dart';

class HeartRatePage extends StatelessWidget {
  HeartRatePage({super.key});

  final logic = Get.find<HeartRateLogic>();
  final state = Get.find<HeartRateLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: BackBtnIcon(onTap: () => Get.back()),
        actions: [
          GetBuilder<HeartRateLogic>(
            id: 'calendar_btn_icon',
            builder: (_) {
              return _.state.selectedDateType.value == DateType.day
                  ? CalendarBtnIcon(
                      calenderDay: _.state.selectedDate,
                      onTap: () => _showDatePicker(context),
                    )
                  : Container();
            },
          ),
        ],
      ),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        child: ListView(
          children: [
            SizedBox(height: 60.h),
            GetBuilder<HeartRateLogic>(
              id: 'date_type_bar',
              builder: (ctrl) => DateTypeBar(
                initIndex: ctrl.state.dateTypeBarIndex,
                onSelectChanged: (index, dateType) => ctrl.changeDateType(selectedIndex: index, type: dateType),
              ),
            ),
            SizedBox(height: 60.h),
            _buildCalendarContainer(),
            SizedBox(height: 60.h),
            _buildSummary(),
            SizedBox(height: 60.h),
            _buildChart(),
            SizedBox(height: 60.h),
            _buildAvgArea(),
            SizedBox(height: 60.h),
            // Obx(() => state.selectedDateType.value == DateType.day ? _buildHistoryArea() : _buildCycleRatioArea()),
          ],
        ),
      ),
    );
  }

  _buildCalendarContainer() {
    return GetBuilder<HeartRateLogic>(
      id: 'sleep_date_range',
      builder: (ctrl) => Container(
        alignment: Alignment.center,
        child: Text(ctrl.state.dateRangeText),
      ),
    );
  }

  Widget _buildSummary() {
    return Container(
      constraints: BoxConstraints.expand(height: 270.w),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(LocaleKeys.widgets_heart_rate.ts, style: TextStyle(fontSize: 48.sp)),
          GetBuilder<HeartRateLogic>(
            id: 'hr_summary',
            builder: (_) => Text(_.state.currentHR, style: TextStyle(fontSize: 120.sp)),
          ),
        ],
      ),
    );
  }

  Widget _buildChart() {
    return Container(
      constraints: BoxConstraints.expand(height: 700.h),
      decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
      padding: EdgeInsets.fromLTRB(20.w, 50.h, 20.w, 20.h),
      child: GetBuilder<HeartRateLogic>(
        id: 'hr_avg_chart',
        builder: (_) => HrLineChart(summaryList: _.state.hrAvgList.heartRates),
      ),
    );
  }

  Widget _buildAvgArea() {
    return Container(
      constraints: BoxConstraints.expand(height: 620.h),
      padding: EdgeInsets.symmetric(vertical: 40.w, horizontal: 50.w),
      decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: GetBuilder<HeartRateLogic>(
              id: 'hr_avg',
              builder: (_) => Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(logic.getAvgIndicatorText(), style: TextStyle(fontSize: 42.sp, color: Colors.grey)),
                      const Expanded(child: SizedBox()),
                      Text(_.state.hrAvg.heartRateAvg.toString().padLeft(3), style: TextStyle(fontSize: 54.sp)),
                      SizedBox(width: 30.w),
                      Text(LocaleKeys.hr_unit.ts, style: TextStyle(fontSize: 42.sp)),
                    ],
                  ),
                  // SizedBox(height: 15.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(logic.getMaxIndicatorText(), style: TextStyle(fontSize: 42.sp, color: Colors.grey)),
                      const Expanded(child: SizedBox()),
                      Text(_.state.hrAvg.heartRateMax.toString().padLeft(3), style: TextStyle(fontSize: 54.sp)),
                      SizedBox(width: 30.w),
                      Text(LocaleKeys.hr_unit.ts, style: TextStyle(fontSize: 42.sp)),
                    ],
                  ),
                  // SizedBox(height: 15.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(logic.getMinIndicatorText(), style: TextStyle(fontSize: 42.sp, color: Colors.grey)),
                      const Expanded(child: SizedBox()),
                      Text(_.state.hrAvg.heartRateMin.toString().padLeft(3), style: TextStyle(fontSize: 54.sp)),
                      SizedBox(width: 30.w),
                      Text(LocaleKeys.hr_unit.ts, style: TextStyle(fontSize: 42.sp)),
                    ],
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 25.h),
          GetBuilder<HeartRateLogic>(
            id: 'hr_avg_line_bar',
            builder: (_) => Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  logic.getAvgBarTitle(),
                  style: TextStyle(color: Colors.black.withOpacity(0.8), fontWeight: FontWeight.w900, fontSize: 54.sp),
                ),
                SizedBox(height: 10.h),
                LayoutBuilder(
                  builder: (context, constraints) {
                    double width = constraints.maxWidth / 5;
                    int fillWidth = _.state.hrAvg.heartRateAvg <= 0 ? 0 : _.state.hrAvg.heartRateAvg + 39;
                    return Column(
                      children: [
                        StackedLineIndicator(
                          minHeight: 20.h,
                          borderRadius: BorderRadius.circular(10.r),
                          stackedItems: [
                            StackedLineModel(
                              color: Colors.red,
                              width: width,
                              text: Text('0 ~ 40', style: TextStyle(fontSize: 32.sp, color: Colors.grey)),
                            ),
                            StackedLineModel(
                              color: Colors.cyan,
                              width: width,
                              text: Text('41 ~ 80', style: TextStyle(fontSize: 32.sp, color: Colors.grey)),
                            ),
                            StackedLineModel(
                              color: Colors.greenAccent,
                              width: width,
                              text: Text('81 ~ 120', style: TextStyle(fontSize: 32.sp, color: Colors.grey)),
                            ),
                            StackedLineModel(
                              color: Colors.amber,
                              width: width,
                              text: Text('121 ~ 160', style: TextStyle(fontSize: 32.sp, color: Colors.grey)),
                            ),
                            StackedLineModel(
                              color: Colors.red,
                              width: width,
                              text: Text('161 ~ 200', style: TextStyle(fontSize: 32.sp, color: Colors.grey)),
                            ),
                          ],
                        ),
                        Row(
                          children: [
                            SizedBox(width: fillWidth.toDouble()),
                            Image.asset('assets/images/home/triangle.png', color: Colors.red, width: 30.w, height: 30.w),
                          ],
                        )
                      ],
                    );
                  },
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHistoryArea() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(children: [
          Image.asset('assets/images/home/hr_1.png', width: 30.w, height: 60.w),
          SizedBox(width: 20.w),
          Text(LocaleKeys.hr_day_history_title.ts, style: TextStyle(fontSize: 54.sp)),
        ]),
        SizedBox(height: 20.h),
        Obx(
          () => ListView.separated(
            shrinkWrap: true,
            itemCount: min(10, logic.state.hrSummary.value.heartRates.length),
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) => Container(
              height: 140.h,
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 50.w),
              decoration: BoxDecoration(color: Colors.white70.withOpacity(1), borderRadius: BorderRadius.circular(40.r)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(getTime(logic.state.hrSummary.value.heartRates[index].calendarTime),
                      style: TextStyle(fontSize: 48.sp, color: ColorConst.btnFontColor)),
                  Row(
                    children: [
                      Container(
                        width: 68.w,
                        height: 68.w,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(50),
                          color: ColorConst.dialogBtnBg,
                        ),
                        margin: EdgeInsets.only(right: 45.w),
                      ),
                      Text('${logic.state.hrSummary.value.heartRates[index].heartRate}',
                          style: TextStyle(fontSize: 54.sp, color: ColorConst.btnFontColor)),
                    ],
                  ),
                  Text(getDate(logic.state.hrSummary.value.heartRates[index].calendarTime),
                      style: TextStyle(fontSize: 48.sp, color: ColorConst.secondaryFontColor)),
                ],
              ),
            ),
            separatorBuilder: (context, index) => SizedBox(height: 30.h),
          ),
        ),
      ],
    );
  }

  String getTime(String formattedString) {
    if (formattedString.isEmpty) {
      return '00:00';
    }
    DateTime dateTime = DateTime.parse(formattedString);
    return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  String getDate(String formattedString) {
    if (formattedString.isEmpty) {
      return '';
    }
    DateTime dateTime = DateTime.parse(formattedString);
    return '${dateTime.month.toString().padLeft(2, '0')}/${dateTime.day.toString().padLeft(2, '0')}';
  }

  Widget _buildCycleRatioArea() {
    return Column(
      children: [
        Row(
          children: [
            Image.asset('assets/images/home/hr_1.png', width: 30.w, height: 45.w),
            Text(logic.getCycleRatioTitle()),
          ],
        ),
        SizedBox(height: 20.h),
        Container(
          padding: EdgeInsets.symmetric(vertical: 35.w, horizontal: 50.w),
          constraints: BoxConstraints.expand(height: 150.h),
          decoration: BoxDecoration(color: Colors.white70.withOpacity(0.9), borderRadius: BorderRadius.circular(40.r)),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Image.asset('assets/images/home/cycle_ratio_bar.png'),
              Image.asset('assets/images/home/cycle_ratio_bar.png'),
            ],
          ),
        )
      ],
    );
  }

  /// 点击右上角日历图标，打开日历选择
  _showDatePicker(BuildContext context) {
    Get.dialog(
      TableCalendarDialog(
        onEvenLoad: (day) => logic.onCalendarEventLoad(day),
      ),
      barrierColor: Colors.black.withOpacity(.8),
    ).then((value) => logic.datePicker(value));
  }
}
